<template>
  <view class="user-profile">
    <!-- 头像编辑 -->
    <view class="avatar-section">
      <view class="avatar-box">
        <image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
        <view class="avatar-edit" @click="chooseAvatar">
          <text class="iconfont">📷</text>
        </view>
      </view>
      <text class="avatar-tip">点击更换头像</text>
    </view>

    <!-- 基本信息 -->
    <view class="info-section">
      <view class="section-title">基本信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="label">昵称</text>
          <input class="input" v-model="userInfo.nickname" placeholder="请输入昵称" />
        </view>
        <view class="info-item">
          <text class="label">账号</text>
          <input class="input" v-model="userInfo.account" placeholder="请输入账号" />
        </view>
        <view class="info-item">
          <text class="label">性别</text>
          <picker class="picker" :range="genderOptions" :value="genderIndex" @change="onGenderChange">
            <text class="picker-text">{{ genderOptions[genderIndex] }}</text>
          </picker>
        </view>
        <view class="info-item">
          <text class="label">生日</text>
          <picker class="picker" mode="date" :value="userInfo.birthday" @change="onBirthdayChange">
            <text class="picker-text">{{ userInfo.birthday || '请选择生日' }}</text>
          </picker>
        </view>
      </view>
    </view>

    <!-- 联系方式 -->
    <view class="info-section">
      <view class="section-title">联系方式</view>
      <view class="info-list">
        <view class="info-item">
          <text class="label">手机号</text>
          <input class="input" v-model="userInfo.phonenumber" placeholder="请输入手机号" type="number" maxlength="11" />
        </view>
        <view class="info-item">
          <text class="label">邮箱</text>
          <input class="input" v-model="userInfo.email" placeholder="请输入邮箱" type="text" />
        </view>
      </view>
    </view>

    <!-- 地区信息 -->
    <view class="info-section">
      <view class="section-title">地区信息</view>
      <view class="info-list">
        <view class="info-item" @click="showRegionPicker">
          <text class="label">地区选择</text>
          <view class="picker">
            <text class="picker-text">{{ regionText || '请选择省市县' }}</text>
          </view>
          <text class="iconfont right-icon">›</text>
        </view>
      </view>
    </view>

    <!-- 个人简介 -->
    <view class="info-section">
      <view class="section-title">个人简介</view>
      <view class="description-box">
        <textarea class="description-input" v-model="userInfo.description" placeholder="介绍一下自己吧" maxlength="200" />
        <text class="description-count">{{ userInfo.description?.length || 0 }}/200</text>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="button-section">
      <button class="save-btn" @click="handleSave">保存修改</button>
    </view>

    <!-- 省市区选择弹窗 -->
    <view class="region-picker-popup" v-if="showRegion">
      <view class="region-picker-mask" @click="cancelRegionPicker"></view>
      <view class="region-picker-content">
        <view class="region-picker-header">
          <view class="region-picker-cancel" @click="cancelRegionPicker">取消</view>
          <view class="region-picker-title">选择省市县</view>
          <view class="region-picker-confirm" @click="confirmRegionPicker">确定</view>
        </view>
        <view class="region-picker-body">
          <view class="region-picker-column">
            <scroll-view scroll-y class="region-picker-scroll">
              <view 
                v-for="(province, index) in regionData" 
                :key="province.code" 
                class="region-picker-item"
                :class="{ 'active': currentRegion.provinceIndex === index }"
                @click="selectProvince(index)"
              >
                {{ province.name }}
              </view>
            </scroll-view>
          </view>
          <view class="region-picker-column">
            <scroll-view scroll-y class="region-picker-scroll">
              <view 
                v-for="(city, index) in cities" 
                :key="city.code" 
                class="region-picker-item"
                :class="{ 'active': currentRegion.cityIndex === index }"
                @click="selectCity(index)"
              >
                {{ city.name }}
              </view>
            </scroll-view>
          </view>
          <view class="region-picker-column">
            <scroll-view scroll-y class="region-picker-scroll">
              <view 
                v-for="(area, index) in areas" 
                :key="area.code" 
                class="region-picker-item"
                :class="{ 'active': currentRegion.areaIndex === index }"
                @click="selectArea(index)"
              >
                {{ area.name }}
              </view>
            </scroll-view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { uploadFile } from '@/api/upload';
import regionData from '@/utils/region-data.js'; // 引入省市区数据
const userStore = useUserStore();

// 用户信息
const userInfo = ref({
  avatar: '',
  nickname: '',
  gender: 0,
  birthday: '',
  phonenumber: '',
  email: '',
  country: '',
  province: '',
  city: '',
  description: '',
  account: ''
});

// 性别选项
const genderOptions = ['未设置', '男', '女'];
const genderIndex = ref(0);

// 地区选择相关
const showRegion = ref(false);
const currentRegion = ref({
  provinceIndex: 0,
  cityIndex: 0,
  areaIndex: 0,
  province: '',
  city: '',
  area: ''
});

// 计算属性：显示的地区文本
const regionText = computed(() => {
  if (userInfo.value.province && userInfo.value.city) {
    return `${userInfo.value.province} ${userInfo.value.city} ${userInfo.value.country || ''}`;
  }
  return '';
});

// 计算属性：当前选中省份的城市列表
const cities = computed(() => {
  if (regionData && regionData[currentRegion.value.provinceIndex]) {
    return regionData[currentRegion.value.provinceIndex].children || [];
  }
  return [];
});

// 计算属性：当前选中城市的区县列表
const areas = computed(() => {
  if (cities.value && cities.value[currentRegion.value.cityIndex]) {
    return cities.value[currentRegion.value.cityIndex].children || [];
  }
  return [];
});

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 首先检查store中是否已有用户信息
    if (userStore.getUserInfo) {
      const storeUserInfo = userStore.getUserInfo;
      // 防止null值
      if (storeUserInfo) {
        userInfo.value = {
          avatar: storeUserInfo.avatar || '',
          nickname: storeUserInfo.nickname || '',
          gender: storeUserInfo.gender || 0,
          birthday: storeUserInfo.birthday || '',
          phonenumber: storeUserInfo.phonenumber || '',
          email: storeUserInfo.email || '',
          country: storeUserInfo.country || '',
          province: storeUserInfo.province || '',
          city: storeUserInfo.city || '',
          description: storeUserInfo.description || '',
          account: storeUserInfo.account || ''
        };
        genderIndex.value = userInfo.value.gender || 0;
        
        // 如果有省市区信息，尝试匹配并设置当前选中的索引
        if (userInfo.value.province && userInfo.value.city) {
          findRegionIndices();
        }
        return;
      }
    }

    // 如果store没有，则从API获取
    const data = await userStore.fetchUserInfo();
    // 确保data存在
    if (data) {
      userInfo.value = {
        avatar: data.avatar || '',
        nickname: data.nickname || '',
        gender: data.gender || 0,
        birthday: data.birthday || '',
        phonenumber: data.phonenumber || '',
        email: data.email || '',
        country: data.country || '',
        province: data.province || '',
        city: data.city || '',
        description: data.description || '',
        account: data.account || ''
      };
      genderIndex.value = userInfo.value.gender || 0;
      
      // 如果有省市区信息，尝试匹配并设置当前选中的索引
      if (userInfo.value.province && userInfo.value.city) {
        findRegionIndices();
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    // 如果是未登录错误，返回上一页
    if (error.message === '未登录，请先登录') {
      uni.navigateBack();
    }
  }
};

// 根据用户现有的省市区信息，找到对应的索引
const findRegionIndices = () => {
  // 查找省份索引
  const provinceIndex = regionData.findIndex(
    p => p.name === userInfo.value.province
  );
  
  if (provinceIndex !== -1) {
    currentRegion.value.provinceIndex = provinceIndex;
    
    // 查找城市索引
    const provinces = regionData[provinceIndex];
    if (provinces && provinces.children) {
      const cityIndex = provinces.children.findIndex(
        c => c.name === userInfo.value.city
      );
      
      if (cityIndex !== -1) {
        currentRegion.value.cityIndex = cityIndex;
        
        // 查找区县索引，现在存储在country字段中
        const cities = provinces.children[cityIndex];
        if (cities && cities.children && userInfo.value.country) {
          const areaIndex = cities.children.findIndex(
            a => a.name === userInfo.value.country
          );
          
          if (areaIndex !== -1) {
            currentRegion.value.areaIndex = areaIndex;
          }
        }
      }
    }
  }
};

onMounted(() => {
  // 检查登录状态
  if (!userStore.getLoginStatus) {
    userStore.checkLoginStatus();
  }
  fetchUserInfo();
});

// 选择头像
const chooseAvatar = async () => {
  try {
    const res = await new Promise((resolve, reject) => {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: resolve,
        fail: reject
      })
    })

    const [tempFile] = res.tempFiles
    if (tempFile.size > 2 * 1024 * 1024) {
      return uni.showToast({ title: '图片需小于2MB', icon: 'none' })
    }

    uni.showLoading({ title: '上传中...', mask: true })

    // 1. 执行上传
    const uploadRes = await uploadFile(res.tempFilePaths[0])
    console.log('上传响应:', uploadRes)

    // 检查是否成功 - 修改为新的API响应格式
    if (uploadRes.code !== 200 || !uploadRes.data?.url) {
      throw new Error(uploadRes.message || '获取头像地址失败')
    }

    // 2. 更新用户信息，需要同时发送nickname和avatar
    // 检查是否有昵称，如果没有则尝试从store获取
    if (!userInfo.value.nickname && userStore.getUserInfo?.nickname) {
      userInfo.value.nickname = userStore.getUserInfo.nickname
    }
    
    // 如果仍然没有昵称，提示用户填写
    if (!userInfo.value.nickname) {
      uni.hideLoading()
      uni.showToast({
        title: '请先输入昵称再更新头像',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    const updateData = {
      nickname: userInfo.value.nickname, // 必填项
      avatar: uploadRes.data.url
    }
    
    const updateRes = await userStore.updateUserInfo(updateData)

    // 3. 确认服务端更新成功后更新本地
    if (updateRes && updateRes.code === 200) {
      // 使用上传成功的URL更新本地头像
      userInfo.value.avatar = uploadRes.data.url
      uni.showToast({ title: '头像更新成功', icon: 'success' })
    } else {
      throw new Error(updateRes?.message || '更新用户信息失败')
    }

  } catch (err) {
    console.error('头像上传失败:', err)
    uni.showToast({
      title: err.message || '上传失败',
      icon: 'none',
      duration: 3000
    })
  } finally {
    uni.hideLoading()
  }
}

// 性别选择
const onGenderChange = (e) => {
  genderIndex.value = e.detail.value;
  userInfo.value.gender = parseInt(e.detail.value);
};

// 生日选择
const onBirthdayChange = (e) => {
  userInfo.value.birthday = e.detail.value;
};

// 显示地区选择器
const showRegionPicker = () => {
  showRegion.value = true;
};

// 取消地区选择
const cancelRegionPicker = () => {
  showRegion.value = false;
};

// 确认地区选择
const confirmRegionPicker = () => {
  const province = regionData[currentRegion.value.provinceIndex];
  const city = cities.value[currentRegion.value.cityIndex];
  const area = areas.value[currentRegion.value.areaIndex];
  
  userInfo.value.province = province ? province.name : '';
  userInfo.value.city = city ? city.name : '';
  userInfo.value.country = area ? area.name : '';
  
  showRegion.value = false;
};

// 选择省份
const selectProvince = (index) => {
  if (currentRegion.value.provinceIndex !== index) {
    currentRegion.value.provinceIndex = index;
    currentRegion.value.cityIndex = 0;
    currentRegion.value.areaIndex = 0;
  }
};

// 选择城市
const selectCity = (index) => {
  if (currentRegion.value.cityIndex !== index) {
    currentRegion.value.cityIndex = index;
    currentRegion.value.areaIndex = 0;
  }
};

// 选择区县
const selectArea = (index) => {
  currentRegion.value.areaIndex = index;
};

// 保存修改
const handleSave = async () => {
  // 表单验证
  if (!userInfo.value.nickname || userInfo.value.nickname.trim() === '') {
    uni.showToast({
      title: '请输入昵称',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  if (userInfo.value.phonenumber && !/^1[3-9]\d{9}$/.test(userInfo.value.phonenumber)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none',
      duration: 2000
    });
    return;
  }
 // 表单验证
 if (!userInfo.value.account || userInfo.value.account.trim() === '') {
    uni.showToast({
      title: '请输入账号',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  if (userInfo.value.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userInfo.value.email)) {
    uni.showToast({
      title: '请输入正确的邮箱',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  // 显示加载中
  uni.showLoading({
    title: '保存中...'
  });

  try {
    // 创建更新数据对象，只包含有值的字段
    const updateData = {
      // 昵称是必填项
      nickname: userInfo.value.nickname,
      account: userInfo.value.account
    };

    // 仅添加有值的字段
    if (userInfo.value.avatar) updateData.avatar = userInfo.value.avatar;
    if (userInfo.value.gender !== undefined && userInfo.value.gender !== null) updateData.gender = userInfo.value.gender;
    if (userInfo.value.birthday) updateData.birthday = userInfo.value.birthday;
    if (userInfo.value.phonenumber) updateData.phonenumber = userInfo.value.phonenumber;
    if (userInfo.value.email) updateData.email = userInfo.value.email;
    if (userInfo.value.country) updateData.country = userInfo.value.country;
    if (userInfo.value.province) updateData.province = userInfo.value.province;
    if (userInfo.value.city) updateData.city = userInfo.value.city;
    if (userInfo.value.description) updateData.description = userInfo.value.description;

    const result = await userStore.updateUserInfo(updateData);

    if (result && result.code === 200) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      });

      setTimeout(() => {
        uni.navigateBack();
      }, 2000);
    } else {
      throw new Error(result?.message || '保存失败');
    }
  } catch (error) {
    console.error('保存用户信息失败:', error);
    uni.showToast({
      title: error.message || '保存失败，请稍后重试',
      icon: 'none',
      duration: 3000
    });
  } finally {
    uni.hideLoading();
  }
};
</script>

<style>
.user-profile {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
  background-color: #ffffff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.avatar-box {
  position: relative;
  margin-bottom: 20rpx;
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 80rpx;
}

.avatar-edit {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 50rpx;
  height: 50rpx;
  background-color: #007AFF;
  border-radius: 25rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
}

.avatar-tip {
  font-size: 24rpx;
  color: #999;
}

.info-section {
  background-color: #ffffff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 20rpx 0;
}

.section-title {
  padding: 0 30rpx;
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.info-list {
  padding: 0 30rpx;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  width: 140rpx;
  font-size: 28rpx;
  color: #333;
}

.input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.picker {
  flex: 1;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.right-icon {
  font-size: 32rpx;
  color: #999;
  margin-left: 10rpx;
}

.description-box {
  padding: 0 30rpx;
  position: relative;
}

.description-input {
  width: 100%;
  height: 200rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
}

.description-count {
  position: absolute;
  right: 50rpx;
  bottom: 20rpx;
  font-size: 24rpx;
  color: #999;
}

.button-section {
  padding: 40rpx 20rpx;
}

.save-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #007AFF;
  color: #ffffff;
  border-radius: 40rpx;
  font-size: 32rpx;
}

/* 地区选择器样式 */
.region-picker-popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
}

.region-picker-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.region-picker-content {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 600rpx;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
}

.region-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 90rpx;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
}

.region-picker-title {
  font-size: 30rpx;
  font-weight: bold;
}

.region-picker-cancel, .region-picker-confirm {
  font-size: 28rpx;
  color: #007AFF;
}

.region-picker-body {
  display: flex;
  height: 510rpx;
}

.region-picker-column {
  flex: 1;
  height: 100%;
  border-right: 1rpx solid #eee;
}

.region-picker-column:last-child {
  border-right: none;
}

.region-picker-scroll {
  height: 100%;
}

.region-picker-item {
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.region-picker-item.active {
  color: #007AFF;
  background-color: #f5f5f5;
}
</style>
